#coding:utf8
"""

"""
import logging
import time
import os


class Log(object):
    '''
    封装后的logging
    '''

    def __init__(self, name=None, file_name=None):
        '''
            指定保存日志的文件路径，日志级别，以及调用文件
            将日志存入到指定的文件中
        '''

        # 创建一个logger
        self.logger = logging.getLogger(name)
        self.logger.setLevel(logging.DEBUG)
        self.logger.propagate = False  # 防止终端重复打印
        # 创建一个handler，用于写入日志文件
        self.log_time = time.strftime("%Y_%m_%d")
        # 定义handler的输出格式
        formatter = logging.Formatter(
            '[%(asctime)s] %(filename)s->%(funcName)s line:%(lineno)d [%(levelname)s]%(message)s')

        if not self.logger.handlers:
            # 创建一个handler，用于输出到控制台
            ch = logging.StreamHandler()
            ch.setLevel(logging.INFO)
            ch.setFormatter(formatter)
            self.logger.addHandler(ch)

            if file_name:
                file_dir = os.getcwd() + '/log'
                if not os.path.exists(file_dir):
                    os.mkdir(file_dir)
                self.log_path = file_dir
                self.log_name = self.log_path + "/" + file_name + "_" + self.log_time + '.log'

                #fh = logging.FileHandler(self.log_name, 'a')  # 追加模式  这个是python2的
                fh = logging.FileHandler(self.log_name, 'a', encoding='utf-8')  # 这个是python3的
                fh.setLevel(logging.INFO)
                fh.setFormatter(formatter)
                self.logger.addHandler(fh)


    def getlog(self):
        return self.logger


def get_logger(logger_name='root', log_path=None, level=None):
    """得到日志对象"""
    logger = logging.getLogger(logger_name)
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter('[ %(asctime)s ] - %(levelname)s - %(message)s')

    if not logger.handlers:
        ch = logging.StreamHandler()
        ch.setLevel(logging.INFO)
        ch.setFormatter(formatter)
        logger.addHandler(ch)

        if log_path:
            fh = logging.FileHandler(log_path, 'a', encoding='utf8')
            fh.setLevel(logging.INFO)
            fh.setFormatter(formatter)
            logger.addHandler(fh)

    return logger


if __name__=="__main__":
    logger_name = "dg"
    log_path = "test-log.log"
    level = logging.INFO

    loggor = get_logger(logger_name, log_path, level)
    loggor.info("hello")
    loggor.warning("python")